var vm = new Vue({
    el: "#app",
    data: {
        localUrl : "http://192.168.2.163",
        neo4jd3: '',//neo4jd3对象
        neo4jd3Data: {},//neo4jd3对象
        leftTreeData: [],
        defaultProps: {
            children: 'children', // 子节点的字段名
            label: 'title' // 指定label字段的别名
        },
        leftTreeCheckedKeys2:[],//所有默认选择的key
        leftTreeCheckedKeys:[],//所有默认选择的key
        searchIndex: 1,
        label: "搜索3DTILES服务:search",
    },
    mounted: function() {
        this.loadData();
    },
    methods: {
        /**
         *入口url，获取图谱关系url与参数，拼接成get请求
         *
         */
        getRequestUrl: function(){
            //取浏览器地址栏的参数
            var buildingId = this.getQueryStringParameter('buildingId');
            var contentId = this.getQueryStringParameter('contentId');

            //请求接口
            var requestUrl = this.localUrl + ":9800/rest/3dtiles/findRelations?contentId=" + contentId;
            // requestUrl = "http://localhost:9800/rest/3dtiles/findRelations?contentId=1afe019b-7233-41cc-a31e-42890d45bb05";
            // buildingId = '231018';

            if (buildingId != undefined && buildingId != null) {
                requestUrl += "&buildingId=" + buildingId;
            }
            return requestUrl;
        },
        /**
         * 从url中，获取参数
         * @param name
         * @returns {string}
         */
        getQueryStringParameter: function(name){
            var regex = new RegExp('[?&]' + name + '=([^&]+)');
            var match = window.location.search.match(regex);
            return match ? decodeURIComponent(match[1]) : "";
        },
        loadData: function() {
            var t = this;
            var requestUrl = t.getRequestUrl();

            fetch(requestUrl, {
                method: 'get',
            })
            .then(response => response.json())
            .then(data => {
                    t.neo4jd3Data = data;
                    t.initLeftTree(data);
                    t.initGraph(data);
            })
            .catch((error) => {
                    console.error('Error:', error);
            });
        },
        //案例来源：https://github.com/eisman/neo4jd3
        initGraph: function(data){
            neo4jd3 = new Neo4jd3('#neo4jd3', {
                highlight: [
                    {
                        class: 'Project',
                        property: 'name',
                        value: 'neo4jd3'
                    }, {
                        class: 'Person',
                        property: 'name',
                        value: 'Emil'
                    }
                ],
//             icons: {
// //                        'Address': 'home',
//                 'Api': 'gear',
// //                        'BirthDate': 'birthday-cake',
//                 'Cookie': 'paw',
// //                        'CreditCard': 'credit-card',
// //                        'Device': 'laptop',
//                 'Email': 'at',
//                 'Git': 'git',
//                 'Github': 'github',
//                 'Google': 'google',
// //                        'icons': 'font-awesome',
//                 'Ip': 'map-marker',
//                 'Issues': 'exclamation-circle',
//                 'Language': 'language',
//                 'Options': 'sliders',
//                 'Password': 'lock',
//                 'Phone': 'phone',
//                 'Project': 'folder-open',
//                 'SecurityChallengeAnswer': 'commenting',
//                 'User': 'user',
//                 'zoomFit': 'arrows-alt',
//                 'zoomIn': 'search-plus',
//                 'zoomOut': 'search-minus'
//             },
                images: {
                    // 'AgSrvContent':'img/AgSrvContent.svg',
                    // 'AgSrvUnityId':'img/AgSrvUnityId.png',
                    // 'Agcim3dbuilding':'img/Agcim3dbuilding.svg',
                    // 'AgSrvContentDraw':'img/AgSrvContentDraw.svg'
//                 'Address': 'img/twemoji/1f3e0.svg',
// //                        'Api': 'img/twemoji/1f527.svg',
//                 'BirthDate': 'img/twemoji/1f382.svg',
//                 'Cookie': 'img/twemoji/1f36a.svg',
//                 'CreditCard': 'img/twemoji/1f4b3.svg',
//                 'Device': 'img/twemoji/1f4bb.svg',
//                 'Email': 'img/twemoji/2709.svg',
//                 'Git': 'img/twemoji/1f5c3.svg',
//                 'Github': 'img/twemoji/1f5c4.svg',
//                 'icons': 'img/twemoji/1f38f.svg',
//                 'Ip': 'img/twemoji/1f4cd.svg',
//                 'Issues': 'img/twemoji/1f4a9.svg',
//                 'Language': 'img/twemoji/1f1f1-1f1f7.svg',
//                 'Options': 'img/twemoji/2699.svg',
//                 'Password': 'img/twemoji/1f511.svg',
// //                        'Phone': 'img/twemoji/1f4de.svg',
//                 'Project': 'img/twemoji/2198.svg',
//                 'Project|name|neo4jd3': 'img/twemoji/2196.svg',
// //                        'SecurityChallengeAnswer': 'img/twemoji/1f4ac.svg',
//                 'User': 'img/twemoji/1f600.svg'
// //                        'zoomFit': 'img/twemoji/2194.svg',
// //                        'zoomIn': 'img/twemoji/1f50d.svg',
// //                        'zoomOut': 'img/twemoji/1f50e.svg'
                },
                minCollision: 60,
                //直接设置数据的方式
                neo4jData: data,
                //直接设置url的方式
                // neo4jDataUrl: requestUrl,
                nodeRadius: 30,
                //Show the information panel: true, false. Default: true.
                infoPanel: true,
                //自定义把属性展示在图形内，names数组是perperties的展示属性名，show=true则展示
                showPropertiesName: {show: true, names: ['contentTitle','dataName','contentDrawName','buildingname','name']},
                //可指定颜色
                // colors: ["#FF0000","#FFA500","#0000FF","#800080",'#ff75ea'],
                onNodeDoubleClick: function(node) {
                    // switch(node.id) {
                    //     case '25':
                    //         // Google
                    //         window.open(node.properties.url, '_blank');
                    //         break;
                    //     default:
                    //         var maxNodes = 5,
                    //             data = neo4jd3.randomD3Data(node, maxNodes);
                    //         neo4jd3.updateWithD3Data(data);
                    //         break;
                    // }
                    vm.search3dtiles(node);
                },
                onRelationshipDoubleClick: function(relationship) {
                    console.log('double click on relationship: ' + JSON.stringify(relationship));
                },

                zoomFit: false
            });
        },
        /**
         * 查询3dtles数据，查询是es查询
         */
        search3dtiles: function (node) {
            var key = "";
            if (node.labels != undefined && node.labels[0].indexOf("AgSrvContent") != -1) {
                key = node.properties.contentTitle;
            }
            if (key == "" || key == undefined){
                return;
            }
            var table = "ag_srv_content";
            var formData = new FormData();
            formData.append("key", key);
            formData.append("table", table);
            fetch(vm.localUrl + ':8899/search', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                 //得到结果后，只展示前10条
                 if (data.status == 200) {
                    var data = data.data;
                    if (data == null || data.length == 0) {
                        return;
                    }
                    var contentDatas = data[0];
                    if (contentDatas.type != table) {
                        return;
                    }
                    var contentDataList = contentDatas.list;
                    var results = vm.format3dtilesDataToD3Data(node, contentDataList);

                    //隐藏掉除了当前节点之外的其他节点
                    // vm.hideOtherNodeAndRelations(node);
                    //更新节点图形
                    neo4jd3.updateWithD3Data(results.data);
                    //重绘节点图形
                    // vm.neo4jd3Data.results[0].columns.push(vm.label);
                    // vm.neo4jd3Data.results[0].data[0].graph.nodes.push(...results.data.nodes);
                    // vm.neo4jd3Data.results[0].data[0].graph.relationships.push(...results.data.relationships);
                    // vm.initGraph(vm.neo4jd3Data);
                    //更新左侧树
                    vm.appendDataToRootTree(node.id, results.childrenTreeArr);
                }
            })
            .catch((error) => {
                    console.error('Error:', error);
            });
        },

        /**
         * 格式化，把3dtiles数据，格式化成 D3 data
         * @param d 父节点
         * @param list 3dtiles数据
         * @returns {{relationships: [], nodes: []}}
         */
        format3dtilesDataToD3Data: function (d, list) {
            var data = {
                nodes: [],
                relationships: []
            },  node, numNodes = 10, relationship ;
            var s = neo4jd3.size();
            if (list.length < 10) {
                numNodes = list.length;
            }
            var childrenTreeArr = [];
            for (var i = 0; i < numNodes; i++) {
                var data3dtiles = list[i];
                delete data3dtiles.contentPath;

                node = {
                    id: s.nodes + 1 + i,
                    labels: [vm.label],
                    properties: data3dtiles,
                    x: d.x,
                    y: d.y
                };

                data.nodes[data.nodes.length] = node;

                relationship = {
                    id: s.relationships + 1 + i,
                    type: vm.label,
                    startNode: d.id,
                    endNode: s.nodes + 1 + i,
                    properties: {
                        "来源": d.properties.contentTitle,
                    },
                    source: d.id,
                    target: s.nodes + 1 + i,
                    linknum: s.relationships + 1 + i
                };
                data.relationships[data.relationships.length] = relationship;

                //组装左侧树
                var childrenTreeObj = {
                    title : data3dtiles.contentTitle ,
                    id : node.id,
                    checked : true,
                    spread : true,
                    root : false,
                }
                childrenTreeArr.push(childrenTreeObj);
            }
            return {data: data, childrenTreeArr: childrenTreeArr};
        },
        /**
         * 隐藏除了当前节点之外的其他节点和关系
         * @param node 当前节点
         */
        hideOtherNodeAndRelations: function (node) {
            var textNodes = document.querySelectorAll('.node');
            var relationships = document.querySelectorAll('.relationship');

            for(var i = 0; i < textNodes.length; i++) {
                var nodeData = textNodes[i].__data__;
                //node：可通过id和位置x,y，只要三个相同，就代表是相同数据
                if (node.id !== nodeData.id && node.x !== nodeData.x && node.y !== nodeData.y) {
                    textNodes[i].style.display = 'none';
                }
                //relationship：可通过其target属性的id和位置x,y，只要三个相同，就代表是相同数据
                var relationData = relationships[i];
                if (relationData == undefined) {
                    continue;
                }
                var targetData = relationData.__data__.target;
                if (node.id !== targetData.id && node.x !== targetData.x && node.y !== targetData.y) {
                    relationships[i].style.display = 'none';
                }
            }
        },

        /**
         * 通过id，隐藏当前node的节点
         * @param node 需要隐藏的节点
         */
        hideNodeAndRelationsById: function (node) {
            var textNodes = document.querySelectorAll('.node');
            var relationships = document.querySelectorAll('.relationship');

            for(var i = 0; i < textNodes.length; i++) {
                var nodeData = textNodes[i].__data__;
                //node：可通过id，就代表是相同数据
                if (node.id == nodeData.id) {
                    textNodes[i].style.display = 'none';
                }
                //relationship：可通过其target属性的id，就代表是相同数据
                var relationData = relationships[i];
                if (relationData == undefined) {
                    continue;
                }
                var targetData = relationData.__data__.target;
                if (node.id === targetData.id) {
                    relationships[i].style.display = 'none';
                }
            }
        },
        /**
         * 通过id，展示当前node的节点
         * @param node 需要展示的节点
         */
        showNodeAndRelationsById: function (node) {
            var textNodes = document.querySelectorAll('.node');
            var relationships = document.querySelectorAll('.relationship');

            for(var i = 0; i < textNodes.length; i++) {
                var nodeData = textNodes[i].__data__;
                //node：可通过id，就代表是相同数据
                if (node.id == nodeData.id) {
                    textNodes[i].style.display = 'block';
                }
                //relationship：可通过其target属性的id，就代表是相同数据
                var relationData = relationships[i];
                if (relationData == undefined) {
                    continue;
                }
                var targetData = relationData.__data__.target;
                if (node.id === targetData.id) {
                    relationships[i].style.display = 'block';
                }
            }
        },
        /**
         * 向父节点中，添加子节点
         *
         * @param parentNodeId 父节点id
         * @param childrenNodeArr 子节点，子节点结构和tree的结构完全一致
         */
        appendDataToRootTree: function(parentNodeId, childrenNodeArr){
            //遍历当前tree数据，找到当前这条数据后，直接添加子节点，一般来说，就是根目录
            var root = vm.leftTreeData[0];
            var children = root.children;
            //对当前结果重新组装一个对象
            var arr = [{
                title : "【搜索3DTILES服务+" + vm.searchIndex + "】" ,
                id : new Date().getTime(),
                checked : true,
                spread : true,
                root : false,
                children : childrenNodeArr,
            }];
            vm.searchIndex++;
            var newChildren = children.concat(arr);
            root.children = newChildren;
            //设置已选中的数据
            for(var i = 0; i < childrenNodeArr.length; i++) {
                vm.leftTreeCheckedKeys.push(childrenNodeArr[i].id);
            }

            vm.$nextTick(() => {
                // 尝试触发更新
                vm.$refs.leftTreeRef.setCheckedKeys(vm.leftTreeCheckedKeys);
            });

        },
        initLeftTree: function (data) {
            let _this = this;
            //组装tree数据
            var nodes = data.results[0].data[0].graph.nodes;
            var root3dtiles = {};
            var agcim3dbuildingArr = [];
            var agcim3dProjectArr = [];
            var agSrvContentDrawArr = [];
            var agsrvContentProjectArr = [];
            var agSrvContentUserArr = [];
            var agSrvUnityIdArr = [];
            for(var i = 0; i < nodes.length; i++) {
                var nodeObj = nodes[i];
                if (nodeObj.labels[0] === '3DTILES服务:AgSrvContent' && root3dtiles.id == undefined) {
                    //作为根目录
                    root3dtiles.title = "【" + nodeObj.labels[0].split(":")[0] + "】" + nodeObj.properties.contentTitle;
                    root3dtiles.id = nodeObj.id;
                    root3dtiles.checked = true;
                    root3dtiles.spread = true;
                    root3dtiles.root = true;
                    _this.leftTreeCheckedKeys.push(root3dtiles.id);
                }
                if (nodeObj.labels[0] === 'AGM服务_建筑表:Agcim3dbuilding') {
                    _this.pushTreeData(agcim3dbuildingArr, nodeObj, "buildingname");
                }
                if (nodeObj.labels[0] === 'AGM服务_项目表:Agcim3dproject') {
                    _this.pushTreeData(agcim3dProjectArr, nodeObj, "name");
                }
                if (nodeObj.labels[0] === '图纸服务:AgSrvContentDraw') {
                    _this.pushTreeData(agSrvContentDrawArr, nodeObj, "contentDrawName");
                }
                if (nodeObj.labels[0] === '所属项目:AgSrvContentProject') {
                    _this.pushTreeData(agsrvContentProjectArr, nodeObj, "name");
                }
                if (nodeObj.labels[0] === '上传者:AgSrvContentUser') {
                    _this.pushTreeData(agSrvContentUserArr, nodeObj, "name");
                }
                if (nodeObj.labels[0] === '统一ID服务:AgSrvUnityId') {
                    _this.pushTreeData(agSrvUnityIdArr, nodeObj, "dataName");
                }
            }
            //组装tree，最多3层，格式已经固定
            if (agcim3dbuildingArr.length != 0) {
                agcim3dbuildingArr[0].children = agcim3dProjectArr;
            }
            //图纸重新组装一层
            var contentDrawArr = [{
                title : "【图纸服务】" ,
                id : new Date().getTime(),
                checked : true,
                spread : true,
                root : false,
                children : agSrvContentDrawArr,
            }];
            _this.leftTreeCheckedKeys.push(contentDrawArr[0].id);

            //把数组进行相加
            var root3dtilesChildren = agcim3dbuildingArr.concat(contentDrawArr)
                .concat(agsrvContentProjectArr)
                .concat(agSrvContentUserArr)
                .concat(agSrvUnityIdArr);
            root3dtiles.children = root3dtilesChildren;
            _this.leftTreeData.push(root3dtiles);

            _this.$nextTick(() => {
                // 尝试触发更新
                _this.leftTreeCheckedKeys2 = _this.leftTreeCheckedKeys;
            });

        },
        pushTreeData: function (arr, nodeObj, keyName) {
            let _this = this;
            //去重
            var distinct = false;
            for(var j = 0; j < arr.length; j++) {
                if (arr[j].id == nodeObj.id) {
                    distinct = true;
                    break;
                }
            }
            if (!distinct) {
                var children = {};
                children.title = "【" + nodeObj.labels[0].split(":")[0] + "】" + nodeObj.properties[keyName];
                children.id = nodeObj.id;
                children.checked = true;
                children.spread = true;
                children.root = false;
                arr.push(children);
                _this.leftTreeCheckedKeys.push(children.id);
            }
        },
        handleCheckChange: function(data, checked, childrenHashChecked) {
            //该节点所对应的对象、节点本身是否被选中、节点的子树中是否有被选中的节点

            vm.leftTreeCheckedKeys = vm.$refs.leftTreeRef.getCheckedKeys();

            //半选择
            var halfCheck = vm.$refs.leftTreeRef.getHalfCheckedKeys();

            //点击复选框，同步图谱
            vm.onchekcLeftBox(vm.leftTreeData[0], vm.leftTreeCheckedKeys, halfCheck);

        },
        /**
         * 点击左侧树的复选框，做相关操作
         * @param data 当前所有树节点
         * @param checkIds 选中的ids
         * @param halfCheckIds 半选中的ids
         */
        onchekcLeftBox: function (data, checkIds, halfCheckIds) {

            //遍历主树节点，判断是否是未选中的，且不是半选择的，就设置节点隐藏，否则就设置显示
            if (data.children != undefined && data.children.length != 0) {
                for(var i = 0; i < data.children.length; i++) {
                    var children = data.children[i];
                    vm.onchekcLeftBox(children, checkIds, halfCheckIds);
                }
            }
            //判断是否已选中
            var disableCheck = false;
            for(var i = 0; i < checkIds.length; i++) {
                if (data.id == checkIds[i]) {
                    disableCheck = true;//当前id已选中
                    break;
                }
            }
            var show = false;//设置节点展示或者隐藏
            if (disableCheck) {
                show = true;//已选中，展示
            } else {
                //未选中，再判断是否是半选择
                var notSelectHalfSelect = false;
                for(var j = 0; j < halfCheckIds.length; j++) {
                    if (data.id == halfCheckIds[j]) {
                        //未选中，又是半隐藏,不做操作
                        notSelectHalfSelect = true;
                        break;
                    }
                }
                if (notSelectHalfSelect) {
                    show = true;
                } else {
                    show = false;
                }
            }
            if (show) {
                vm.showNodeAndRelationsById(data);
            } else {
                vm.hideNodeAndRelationsById(data);
            }
        },
    },
    computed: {
        headMsg: function() {
            return {
                "Authorization": "bearer " + localStorage.getItem("access_token") //设置请求头
            }
        },
    },

});
window.vm = vm;







